<template>
  <div
    style="
      width: 100%;
      height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      margin: auto;
    "
    id="login"
  >
    <div class="login_header">
      <img class="logo" src="static/image/login/login_logo.png" v-if="status" />
    </div>
    <div class="login_main_wrap" v-if="status">
      <!-- 输入账号密码登录页 -->
      <div class="login_main" v-show="loginTab == 0">
        <div class="loginForm">
          <img src="static/image/login/person.png" class="loginLabelImg" />
          <input
            type="text"
            maxlength="16"
            placeholder="输入账号"
            v-model="userName"
            @keyup.enter="keyEnter(1)"
          />
        </div>
        <div class="loginForm" style="margin-top: 16px">
          <img src="static/image/login/password.png" class="loginLabelImg" />
          <input
            type="password"
            style="flex-grow: 1"
            maxlength="18"
            placeholder="输入密码"
            v-model="passWord"
            @keyup.enter="keyEnter(2)"
            ref="passwordInput"
          />
        </div>
        <div class="auto_login">
          <div style="text-align: left">
            记住帐号
            <input
              type="checkbox"
              v-model="remember"
              @click="accountCheck(0)"
              style="
                margin-left: 6px;
                height: 17px;
                width: 17px;
                vertical-align: middle;
                cursor: pointer;
              "
            />
          </div>
          <div style="text-align: right; flex: 1">
            自动登录
            <input
              type="checkbox"
              v-model="autoLogin"
              @click="accountCheck(1)"
              style="
                margin-left: 6px;
                height: 17px;
                width: 17px;
                vertical-align: middle;
                cursor: pointer;
              "
            />
          </div>
        </div>
        <div>
          <div class="login_sub" @click="loginSubmit">登录</div>
          <div class="download_sub">
            <a href="http://222.79.63.199:30030/versionManage/download/IM_PC.exe">点击下载最新版本</a>
          </div>
        </div>
      </div>
      <!-- 扫描二维码登录页 -->
      <div class="login_code" v-show="loginTab == 1">
        <qriously :value="initQCode" :size="200" />
        <!-- 刷新二维码 -->
        <div class="qrcode-error" v-show="qrcodeTab == 1">
          <p>二维码已过期</p>
          <span @click.stop.prevent="upDateQrcode">点击刷新</span>
        </div>
        <div class="code_tip">用即时通讯app扫码登入</div>
      </div>
      <!-- 切换登录方式按钮 -->
      <div
        class="login_tab"
        @click.stop.prevent="tabClick"
        :title="loginTab == 0 ? '扫码登录' : '帐号登录'"
      >
        <img
          :src="
            loginTab == 0
              ? 'static/image/login/code_tab.png'
              : 'static/image/login/login_tab.png'
          "
        />
      </div>
    </div>
    <div v-else class="logining_wrap">
      <img :src="loginHeadImg" alt="" class="logining_logo" />
      <p class="logining_tel">{{ userName }}</p>
      <div class="logining_text">
        登陆中<span style="width: 20px; display: inline-block"
          ><span v-for="(i, index) in dotNum" :key="index">.</span></span
        >
      </div>
      <button type="button" class="cancelBtn" @click="cancelLogin">取消</button>
    </div>
    <!-- 账号再其他地方登录提示 -->
    <div v-if="userOutLine" class="outLine_box">
      <div class="outLine_main">
        <p>{{ "账号信息更改或帐号已在其他地方登陆" }}</p>
        <button type="button" @click="userOutLine = false">确定</button>
      </div>
    </div>
  </div>
</template>
<script>
import { Form, FormItem, Input, Button } from "iview";
import { mapState } from "vuex";
import loginHeadImg from "../../static/image/login/head.png";
import { Notification } from "element-ui";
export default {
  components: {
    Form,
    Input,
    FormItem,
    Button
  },
  data() {
    return {
      netErrorTimeout: null, //zk1225新增，网络异常的延时器
      isConnecting: true, //zk新增，当前是否是连接状态
      connectTipFlag: true, //zk新增，重连时是否提醒
      dotNum: 1,
      dotInterval: null,
      loginHeadImg,
      status: true,
      isAutoLogin: false,
      loginTab: 0,
      canLogin: true,
      userNameError: "",
      passwordError: "",
      userName: "",
      passWord: "",
      canMove: false,
      max: false,
      remember: false,
      autoLogin: false,
      lockReconnect: false, //是否真正建立连接
      timeout: 28 * 1000, //28秒一次心跳
      timeoutObj: null, //心跳 定时器
      serverTimeoutObj: null, //心跳服务端阻塞 定时器
      timeoutnum: null, //断开重连 定时器
      linkSuccess: true,
      qrcodeTab: 0, //二维码失效开关
      TimeUpQrode: null, //二维码失效 定时器
      updateQrcodeTime: 5 * 1000 * 60, //二维码失效时间
      proessId: null, // 新增进程ID
      userOutLine: false, //新增被挤下线提示
      outLineSocket: null, //新增断线重连 定时器
      onlyLogin: true, //新增控制登录点击次数
      onlyQcode: true, //新增控制切换二维码发送的socket次数
      outLineSocketNum: 0, //新增断线重连次数
      initLoginButton: null, //新增点击登录请求响应时间 定时器
      intranetIP: "", //内网IP
      timeUpdateAtt: 25 * 60 * 1000, //25分钟更新一次链接
      updateAtt: null, //验签定时器
      updateAttOut: null,
      getWebSockectTime: "", //获取外壳验签地址定时器
      deviceno: "",
      WebSockectUrl: "",
      errorConnectTime: 5, //五分钟超过多少次停止重连
      wsUrl: "",
      wsConnectNum: 0,
      isGetWsUrl: true, //是否获取验签
      refnTimer: "", //重置定时器
      devicenos: "", //上次的设备码
      errGetWsUrl: 0, //wsUrl获取异常错误
      getWsUrlTimeout: "" //延迟定时器
    };
  },
  watch: {
    passWord() {
      this.$store.state.password = this.$func.md5(this.passWord);
    },
    userName() {
      this.$store.state.account = this.userName;
    }
    // '$store.state.wsConnectNum' (value) {
    //   console.log('wsConnectNum变了',value)
    //   this.wsConnectNum = value;
    // },
  },
  computed: {
    ...mapState(["sqlTableArray", "ws", "initQCode"])
  },
  methods: {
    errorConnectTimer() {
      //重置连接异常次数
      if (this.refnTimer) {
        //清除定时器
        clearInterval(this.refnTimer);
      }
      this.refnTimer = setInterval(() => {
        console.log("重置连接异常次数");
        //this.$store.commit('resetWsConnectNum')
        this.wsConnectNum = 0;
      }, 60 * 1000 * this.errorConnectTime);
    },
    getWebSockect() {
      //外壳获取验签
      let dev1 = JSON.parse(this.$shell("GetClientIdentification", []));
      let web1 = JSON.parse(this.$shell("GetEncryptionConfiguration", []));
      if (dev1.return_code != "FALSE" && web1.return_code != "FALSE") {
        this.deviceno = dev1.return_msg;
        this.WebSockectUrl = web1.return_msg.WebSockect[0].Url;
        return true;
      }
    },
    //二维码登录
    tabClick() {
      //新增选择二维码登录时才发送socket
      if (this.onlyQcode) {
        this.onlyQcode = false;
        this.$store.state.ws.send(
          this.$loginJsonString(this.$func.uuid(), "1.100", "1.1.0007", {})
        );
      }
      this.TimeUpQrode && clearTimeout(this.TimeUpQrode);
      if (this.loginTab == 0) {
        this.loginTab = 1;
        // 判断切换时 是否时已经失效
        if (this.qrcodeTab == 1) {
          this.upDateQrcode();
        } else {
          this.TimeUpQrode = setTimeout(() => {
            this.qrcodeTab = 1;
            clearTimeout(this.TimeUpQrode);
          }, this.updateQrcodeTime);
        }
      } else {
        this.loginTab = 0;
        clearTimeout(this.TimeUpQrode);
      }
    },
    // 失效时点击刷新二维码
    upDateQrcode() {
      this.TimeUpQrode && clearTimeout(this.TimeUpQrode);
      this.qrcodeTab = 0;
      this.$store.state.ws.send(
        this.$loginJsonString(this.$func.uuid(), "1.100", "1.1.0007", {})
      );
      this.TimeUpQrode = setTimeout(() => {
        this.qrcodeTab = 1;
        clearTimeout(this.TimeUpQrode);
      }, this.updateQrcodeTime);
    },
    operationalDatabase(statements, index) {
      let to = JSON.stringify({
        Sqlstr: statements
      });
      return arguments[1]
        ? JSON.parse(this.$loginInfo(to, index))
        : JSON.parse(this.$loginInfo(to));
    },
    createLoginTable(id) {
      this.operationalDatabase(
        `CREATE TABLE IF NOT EXISTS users_login(_id INTEGER PRIMARY KEY AUTOINCREMENT,username CHAR(60),password CHAR(60),automatic bit);`
      );
      // var insertAutomatic = this.operationalDatabase(
      //   `ALTER TABLE users_login ADD automaticlogon bit NULL;`
      // );
      // 新增判断表字段（automaticlogon）是否存在
      let automaticlogon = this.operationalDatabase(
        `select * from sqlite_master where name = 'users_login' and sql like 'automaticlogon';`,
        1
      );
      if (automaticlogon.list.length == 0)
        this.operationalDatabase(
          `ALTER TABLE users_login ADD COLUMN automaticlogon;`
        );
    },
    move() {
      if (this.canMove) {
        let a = this.$shell("title_MouseMove", []);
      }
    },
    keyEnter(index) {
      if (index == 1) {
        this.$refs.passwordInput.focus();
      } else if (index == 2) {
        this.loginSubmit();
      }
    },
    dbclick() {
      if (this.max == false) {
        this.$shell("FullScreen_Invoke", []);
        this.max = true;
      } else {
        this.max = false;
        this.$shell("ExitFullScreen_Invoke", []);
      }
    },
    moveStart() {
      this.canMove = true;
      this.$shell("title_MouseDown", []);
    },
    moveEnd() {
      this.canMove = false;
      this.$shell("title_MouseUp", []);
    },
    initMyInfo(info) {
      let userInfo = this.operationalDatabase(`SELECT * FROM users_login;`, 1);
      if (userInfo.list.length > 0 && userInfo.list[0]._id == 1) {
        this.operationalDatabase(
          `UPDATE users_login SET username='${this.userName}',automatic='${
            this.remember ? 1 : 0
          }',
          automaticlogon='${this.autoLogin ? 1 : 0}',password='${
            this.passWord
          }' WHERE _id='1';`
        );
      } else {
        this.operationalDatabase(
          `REPLACE INTO users_login(username,automatic,automaticlogon,password) VALUES ('${
            this.userName
          }','${this.remember ? 1 : 0}','${this.autoLogin ? 1 : 0}','${
            this.passWord
          }');`
        );
      }
      this.$store.commit(
        "setUserInfo",
        Object.assign(info, { myHeadPath: "" })
      );
      console.log("我的信息", info);
      if (this.$route.path != "/home") {
        this.onlyLogin = true; //取消重复点击登录按钮的提示
        this.start(); //启动心跳
        this.initInterval();
        this.lockReconnect = false;
        this.wsConnectNum = 0;
        setTimeout(() => {
          let changeShow = this.$shell("ChangeFormShow", ["1"]);
          this.$router.replace("/home");
        }, 100);
      }
      // 新增获取公文的token
      this.$getOfficialToken(info);
    },
    loginInfo() {
      let identification = this.$shell("GetClientIdentification", []);
      return {
        account: this.$store.state.account,
        password: this.$store.state.password,
        deviceId: this.proessId, // 新增进程ID
        macAddress: JSON.parse(identification).return_msg, // 新增设备ID
        status: "1",
        version: this.$store.state.Version, // 新增版本号
        remoteAddress: this.intranetIP // 新增内网IP
      };
    },
    socketLogin(info, method) {
      try {
        console.log(
          this.$store.state.ws,
          "准备登陆了,this.$store.state.ws",
          this.isConnecting
        );
        this.$store.commit("setLoginInfo", info);
        if (this.$store.state.ws.readyState == "1") {
          setTimeout(() => {
            console.log("发送登录报文1=>");
            this.lockReconnect = true;
            this.$store.state.ws.send(
              this.$loginJsonString(this.$func.uuid(), "1.100", method, {
                loginData: info
              })
            );
          }, 500);
        } else {
          console.log("this.$store.state.ws.readyState异常");
          this.reconnection();
          // this.offlineFn();
          // this.reconnect();
          //this.$Message.warning("未连接成功,请稍后重试",3);
          // setTimeout(() => {
          //   if (
          //     this.$store.state.ws &&
          //     this.$store.state.ws.readyState == "1"
          //   ) {
          //     console.log("发送登录报文2=>");
          //     this.$store.state.ws.send(
          //       this.$loginJsonString(this.$func.uuid(), "1.100", method, {
          //         loginData: info,
          //       })
          //     );
          //   } else {
          //     this.offlineFn();
          //     this.reconnect();
          //   }
          // }, 3000);
        }
      } catch (err) {
        console.log("err", err);
        console.log("this.$store.state.ws异常");
        this.reconnection();
        // this.offlineFn();
        // this.reconnect();
        // this.$Message.warning("登录报文异常重连中,请稍后");
        // this.reconnect();
        // setTimeout(() => {
        //   this.$store.state.ws.send(
        //     this.$loginJsonString(this.$func.uuid(), "1.100", method, {
        //       loginData: info
        //     })
        //   );
        // }, 3000);
      }
    },
    login() {
      let loginInfo = this.loginInfo();
      this.socketLogin(loginInfo, "1.1.0001");
      this.isAutoLogin = false;
      //zk1225登录成功之后清除定时器和计数以及断线提醒的延时器
      this.outLineSocket && clearInterval(this.outLineSocket);
      this.outLineSocketNum = 0;
      this.netErrorTimeout && clearTimeout(this.netErrorTimeout);
    },
    loginSubmit() {
      if (!this.onlyLogin) this.$Message.warning("登录中，请稍后");
      this.$store.state.initStatus = true;
      this.status = false;
      if (this.onlyLogin) {
        // this.$store.commit('resetWsConnectNum');//重置连接次数
        this.wsConnectNum = 0;
        this.lockReconnect = false;
        this.onlyLogin = false;
        let num = 15;
        this.initLoginButton = setInterval(() => {
          num--;
          if (num == 0) {
            this.lockReconnect = true;
            this.$Message.warning("登录请求超时正在重新连接...");
            this.initInterval();
            // 超时关闭 new socket
            this.offlineFn(); //初始化socket
            this.connect();
            clearInterval(this.dotInterval);
            this.status = true;
            this.onlyLogin = true;
            clearInterval(this.initLoginButton);
            if (this.$store.state.ws) {
              this.$store.state.ws.close();
            }
          }
        }, 1000);
        let username = this.userName.replace(/\s/g, "");
        let passWord = this.passWord.replace(/\s/g, "");
        if (username == "") {
          this.$Message.warning("账号不能为空");
          this.onlyLogin = true;
          this.status = true;
          clearInterval(this.dotInterval);
          return;
        } else if (passWord == "") {
          this.$Message.warning("密码不能为空");
          this.onlyLogin = true;
          this.status = true;
          clearInterval(this.dotInterval);
          return;
        }
        if (this.isAutoLogin) return;
        let deviceno = this.deviceno + this.username;
        this.getWsUrl(deviceno);
        this.$createSocket();
      }
    },
    cancelLogin() {
      this.status = true;
      this.onlyLogin = true;
      clearInterval(this.dotInterval);
      clearInterval(this.initLoginButton);
      this.offlineFn();
      // this.reconnect();
    },
    start() {
      console.log("开启心跳");
      this.initStartInterval();
      this.timeoutObj = setTimeout(() => {
        //这里发送一个心跳，后端收到后，返回一个心跳消息
        if (this.$store.state.ws && this.$store.state.ws.readyState == 1) {
          // 连接正常
          let initid = this.$func.uuid();
          this.$store.state.ws.send(
            this.$publicSend(initid, "1.000", "1.1.0001", {})
          );
          console.log("发送心跳");
        } else {
          // 连接异常
          console.log("socket重连");
          this.lockReconnect = false;
          this.reconnect();
        }
        //判断服务端是否阻塞 阻塞关闭链接 生成新的socket
        this.serverTimeoutObj = setInterval(() => {
          console.log("连接超时标记一次");
          // 超时关闭
          this.offlineFn(); //初始化socket
          this.$store.commit("Internet_Err", true); //标记网络链接状态==>未连接
          this.reconnect();
        }, 60 * 1000);
      }, this.timeout);
    },
    reconnection() {
      this.wsConnectNum = 0;
      this.errGetWsUrl = 0;
      this.offlineFn();
      this.lockReconnect = false;
      let deviceno = this.deviceno + this.userName;
      this.getWsUrl(deviceno);
    },
    reconnect() {
      //重新连接,zk标记
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      clearTimeout(this.timeoutnum);
      this.initStartInterval();
      this.wsConnectNum++;
      console.log("this.wsConnectNum", this.wsConnectNum);
      if (this.wsConnectNum >= 5) {
        //断开超过10次,不再重连
        if (this.$route.path == "/home") {
          Notification.closeAll();
          this.$notify({
            title: "错误提示",
            dangerouslyUseHTMLString: true,
            message: `<div>scoket连接失败,请点击重试</div>
                        <button 
                          onclick="reconnection()"
                          style='
                          background-color: #fff;
                          color: #606266;
                          border-radius: 2px;
                          cursor: pointer;
                          border: 1px solid #dcdfe6;
                          padding: 2px 6px;'>重新连接</button>`,
            duration: 0,
            type: "warning",
            showClose: false
          });
        }
        this.isGetWsUrl = true;
        return;
      }
      this.timeoutnum = setTimeout(() => {
        //新连接
        console.log("建立新链接");
        // this.connect();
        let deviceno = this.deviceno + this.userName;
        this.getWsUrl(deviceno);
        this.lockReconnect = false;
      }, 5000);
    },
    onerror() {
      console.log("WebSocket连接发生错误");
      if (this.linkSuccess) {
        if (this.connectTipFlag) {
          //zk修改，延时结束发生连接异常才会提醒
          // this.$Notice.error({
          //   title: "scoket连接发生错误",
          //   duration: 5,
          // });
          this.$store.commit("Internet_Err", true); //标记网络链接状态==>未连接
          this.linkSuccess = false;
        }
        // this.$Notice.error({
        //   title: "网络连接发生错误",
        //   duration: 0
        // });
        // this.$store.commit("Internet_Err", true);//标记网络链接状态==>未连接
        // this.linkSuccess = false;
      }
      try {
        if (this.$store.state.ws) {
          this.$store.state.ws.close();
        }
      } catch (err) {}
      if (this.lockReconnect) return;
      this.initStartInterval();
      this.reconnect();
    },
    onopen() {
      console.log("WS连接上了");
      Notification.closeAll();
      this.wsConnectNum = 0;
      this.linkSuccess = true;
      this.isConnecting = true; //连接之后设置为true
      this.$Notice.destroy(); //清除提示信息
      if (!this.updateAtt) {
        console.log("-----清除登录验签定时器------");
        clearInterval(this.updateAtt);
        clearTimeout(this.updateAttOut);
      }
      this.updateAtt = setInterval(this.updateAttestation, this.timeUpdateAtt);
      this.updateAttOut = setTimeout(this.updateAtt, this.timeUpdateAtt);
      // //加密
      // this.$store.state.ws.send(this.$publicKey(this.$func.uuid(), "1.000", "1.1.0002"))

      if (!this.$store.state.initStatus && this.$store.state.myInfo.id) {
        // 新增判断已经登录的情况下才发送断线重连
        this.outLineSocket && clearInterval(this.outLineSocket);
        let userStatus = this.loginInfo();
        Object.assign(userStatus, {
          status: this.$store.state.updatedUserStatus
        });
        console.log("网络或者服务断开发送断线重连==>>>");
        let sendLoginUserInfo = () => {
          if (this.connectTipFlag) {
            //zk修改，延时结束才会触发计数和消息提醒
            this.outLineSocketNum++;
            this.closeInterval();
          }
          this.socketLogin(userStatus, "1.1.0002");
        };
        sendLoginUserInfo();
        this.outLineSocket = setInterval(sendLoginUserInfo, 10000);
        this.$bus.$emit("isConnected", "连上了/重连了。。。。"); //zk新增，重连时走中央事件总线通知home界面触发获取消息列表方法,zk14修改只有断线才会触发
      } else {
        if (this.$route.path == "/" && !this.onlyLogin) {
          setTimeout(() => {
            this.login();
          }, 1000);
        }
      }
    },
    closeInterval() {
      if (this.outLineSocketNum >= 5) {
        // this.$Message.warning("连接超时，请重新登录");
        this.outLineSocket && clearInterval(this.outLineSocket);
        this.outLineSocketNum = 0; //zk1225，五次提醒之后清掉计数
        // 调用.net接口初始化窗口大小
        this.$shell("SetLoginUser", ["", "", "", "420", "460"]);
        this.$router.replace("/");
        this.offlineFn();
      } else if (this.outLineSocketNum < 5) {
        this.$Message.warning(`尝试重连第${this.outLineSocketNum}次...`);
      }
    },
    onmessage(info) {
      console.log(info, "info12312312321");
      //判断是否收到服务端返回的socket链接消息
      if (info && this.$store.state.internetErr) {
        this.$store.commit("Internet_Err", false); //标记网络链接状态==>已链接
        if (this.linkSuccess) {
          this.$Notice.success({
            title: "scoket已连接",
            duration: 3
          });
          this.onlyLogin = true; //标记是否可以点击登录按钮
          // this.$bus.$emit("isConnected","连上了/重连了。。。。")//zk14修改只有断线重连才会触发
        }
      }
      //收到服务器返回的scoket
      let main = JSON.parse(info.data);
      let head = main.head;
      //解密
      let body = this.$ws_decode(main.body);
      console.log(
        head.action,
        head.method,
        this.$getingTime(),
        main,
        "服务端推送解密"
      );

      let socketInfo = main.info;
      // 写入日志
      let bodyJson = JSON.stringify(body);
      let args = JSON.stringify({
        type: "RECEIVE",
        socketUrl: `${head.action}/${head.method}`,
        args: `userId: [${this.userName}],body: [${bodyJson}]`
      });
      this.$shell("SaveLog", [args]);
      console.log("onmessage start--------------------->1");
      console.log(
        head.action,
        head.method,
        this.$getingTime(),
        main,
        "收到服务器返回的socket"
      );
      if (head.action == "1.000") {
        if (head.method == "1.1.0001") {
          //新增判断心跳是否正常，0异常，1正常
          if (head.resultCode == "0") {
            // 心跳异常
            console.log("心跳异常发送断线重连==>>>");
            this.outLineSocket = setInterval(() => {
              this.outLineSocketNum++;
              //this.socketLogin(this.loginInfo(), "1.1.0002");
              this.closeInterval();
            }, this.timeout);
          } else {
            if (this.$route.path == "/home") {
              // 心跳正常
              console.log("心跳正常11");
              this.start(); //启动心跳
            }
          }
        }
      }
      if (head.resultCode != undefined) {
        if (head.resultCode == "0") {
          this.connect();
          let deviceno = this.deviceno + this.userName;
          this.getWsUrl(deviceno);
          return;
        }
        if (head.action == "1.100") {
          if (head.method == "1.1.0007") {
            this.$store.commit(
              "setInitQCode",
              JSON.parse(info.data).body.qrcode
            );
            return;
          }
          if (head.method == "1.2.0001" && body.offline) {
            if (body.userToken != this.proessId) this.goOutOffline(); // 新增下线判断
          }
          if (head.method == "1.1.0001") {
            if (head.resultCode == 1) {
              if (!socketInfo.success) {
                this.$Message.warning(socketInfo.warnings[0].text);
                this.onlyLogin = true;
                this.status = true;
                this.initInterval(); // 清除定时器
                clearInterval(this.dotInterval);
                return;
              }
              let info = body.userData;
              console.log(info, "登录信息==>", JSON.stringify(main.body));
              localStorage.setItem("access_token", body.access_token);
              this.initMyInfo(info);
            } else {
              this.$Message.warning("请求异常，请稍后再试...");
              console.log(main, "error");
            }
          }
          if (head.method == "1.1.0002") {
            //新增断线重连成功后清除定时器并重置监听链接次数
            this.outLineSocket && clearInterval(this.outLineSocket);
            this.outLineSocketNum = 0;
            if (body.userToken != this.proessId) this.goOutOffline(); // 新增下线判断
            //网络断开后重启心跳
            if (head.resultCode == "1") {
              this.start();
            }
            if (this.$route.path == "/home") {
              this.$getOffline();
              setTimeout(() => {
                this.$getOffline();
              }, 60000);
            }
          }
        }
        if (head.action == "1.500") {
          if (head.method == "1.1.1016") {
            if (!socketInfo.success) {
              this.$store.commit("receiveMessage", main);
            }
          }
        }
        //新增申请入群审核状态返回，zk1215注释，0019接口已废除
        // if (head.action == "1.201") {
        //   if(head.method == "1.1.0019") {
        //     let msg = body.data;
        //     this.$store.commit("Group_Check", msg);
        //   }
        // }
        //新增消息免打扰变更推送返回
        if (head.action == "1.001") {
          if (head.method == "1.2.0015") {
          }
        }
        // this.$store.commit("setSendResult", main);
        this.$store.commit("setSendResult", info.data); // 修改
      } else {
        console.log(main, "消息回执");
        if (
          (head.action == "1.101" && head.method == "1.1.0016") ||
          (head.action == "1.500" && head.method == "1.1.8888")
        ) {
          this.$store.commit("receiveMessage", main);
        }
        this.$store.commit("receiveMessage", main);
      }
    },
    onclose() {
      console.log("ws连接断开");
      window.sendOffline && clearInterval(window.sendOffline);
      this.isConnecting = false; //zk检测到断开时，修改状态
      this.connectTipFlag = false; //zk,断开时到延时结束，不进行重连提醒
      if (!this.updateAtt) {
        console.log("-----清除登录验签------");
        clearInterval(this.updateAtt);
        clearTimeout(this.updateAttOut);
      }
      if (this.$store.state.soketConnect) {
        return;
      }
      try {
        this.$store.state.ws.close();
      } catch (err) {}
      if (this.lockReconnect) {
        return;
      }
      if (this.linkSuccess) {
        this.netErrorTimeout && clearTimeout(this.netErrorTimeout); //zk1225新增，延时器用之前先清
        this.netErrorTimeout = setTimeout(() => {
          //zk新增，延时1分钟提醒
          if (!this.isConnecting) {
            this.$Notice.error({
              title: "scoket连接已断开...",
              duration: 3000
            });
            this.$store.commit("Internet_Err", true); //标记网络链接状态==>未连接
            this.linkSuccess = false;
          }
          this.connectTipFlag = true; //zk延时结束，开启连接提醒
        }, 60000);

        // this.$Notice.error({
        //   title: "连接已断开...",
        //   duration: 0
        // });
        // this.$store.commit("Internet_Err", true);//标记网络链接状态==>未连接
        // this.linkSuccess = false;
      }
      this.initStartInterval();
      setTimeout(() => {
        this.reconnect();
      }, 3000); //ws断开后三秒后开始重连
    },
    connect() {
      //zk注释，ws动作的监听
      //初始化点击登录的按钮，清除定时器
      // this.onlyLogin = true;
      // this.status = true;
      this.initInterval();
      this.lockReconnect = false;
      this.initStartInterval();
    },
    getWsUrl(deviceno = "") {
      if (this.$store.state.ws) {
        this.$store.state.ws.close();
      }
      clearTimeout(this.getWsUrlTimeout);
      //this.WebSockectUrl = "http://172.16.66.21:12000/index/getSignature.do"
      //获取验签
      if (
        deviceno &&
        !this.isGetWsUrl &&
        this.wsUrl &&
        this.devicenos == deviceno
      ) {
        console.log("已经获取验签");
        this.$store.state.ws = new WebSocket(this.wsUrl);
        console.log("ws连接成功1");
        this.$store.state.ws.onopen = this.onopen;
        this.$store.state.ws.onmessage = this.onmessage;
        this.$store.state.ws.onerror = this.onerror;
        this.$store.state.ws.onclose = this.onclose;
        return;
      }
      this.$setWs(this.WebSockectUrl, deviceno)
        .then(res => {
          let data = res.data;
          this.devicenos = deviceno;
          this.isGetWsUrl = false;
          if (data.httpPort) {
            this.$store.state.Url = `http://${data.serverIp}:${data.httpPort}/`;
          }
          this.wsUrl =
            "ws://" +
            data.serverIp +
            ":" +
            data.wssocketPort +
            "/oim/websocket?token=" +
            data.signature +
            "&ip=" +
            data.ip +
            "&deviceno=" +
            deviceno +
            "&timestamp=" +
            data.timestamp;
          if (this.$store.state.isChange) {
            this.wsUrl =
              this.$store.state.socket +
              "?token=" +
              data.signature +
              "&ip=" +
              data.ip +
              "&deviceno=" +
              deviceno +
              "&timestamp=" +
              data.timestamp;
          }
          this.$store.state.ws = new WebSocket(this.wsUrl);
          console.log("获取验签开始连接webscoket", this.$store.state.ws);
          this.$store.state.ws.onopen = this.onopen;
          this.$store.state.ws.onmessage = this.onmessage;
          this.$store.state.ws.onerror = this.onerror;
          this.$store.state.ws.onclose = this.onclose;
          // console.log(
          //   this.$store.state.ws.extensions + "111",
          //   "websocket_实例之extensions"
          // );
          // setTimeout(() => {
          //   console.log(
          //     this.$store.state.ws,
          //     "000",
          //     "websocket_实例之extensions"
          //   );
          // }, 600);
        })
        .catch(error => {
          console.log("获取验签error", error);
          if (this.errGetWsUrl >= 3) {
            return false;
          }
          if (this.$route.path == "/home") {
            Notification.closeAll();
            this.$notify({
              title: "错误提示",
              dangerouslyUseHTMLString: true,
              message: `<div>scoket连接失败,请点击重试</div>
                          <button 
                            onclick="reconnection()"
                            style='
                            background-color: #fff;
                            color: #606266;
                            border-radius: 2px;
                            cursor: pointer;
                            border: 1px solid #dcdfe6;
                            padding: 2px 6px;'>重新连接</button>`,
              duration: 0,
              type: "warning",
              showClose: false
            });
          }
          this.errGetWsUrl++;
          this.getWsUrlTimeout = setTimeout(() => {
            let deviceno = this.deviceno + this.username;
            this.getWsUrl(deviceno);
          }, 10000);
        });
    },
    updateAttestation() {
      console.log("----------更新登录验签----------");
      this.$store.state.ws.send(
        this.$loginJsonString(this.$func.uuid(), "1.000", "1.2.0001", {}) //发送验签
      );
    },
    //退出登录or下线初始化socket
    offlineFn(isLogin = true) {
      if (isLogin) {
        this.lockReconnect = false;
      } else {
        this.lockReconnect = true;
      }
      this.connectTipFlag = false;
      this.wsConnectNum = 0;
      this.initStartInterval();
      if (this.$store.state.ws) {
        this.$store.state.ws.close();
      }
      this.$store.state.ws = null;
    },
    //登录成功后初始化定时器
    initInterval() {
      this.TimeUpQrode && clearInterval(this.TimeUpQrode);
      this.initLoginButton && clearInterval(this.initLoginButton);
    },
    //初始化心跳定时器
    initStartInterval() {
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearInterval(this.serverTimeoutObj);
    },
    //控制是否自动登录、记住账号
    accountCheck(type) {
      if (type === 1 && !this.autoLogin) this.remember = true;
      if (type === 0 && this.remember) this.autoLogin = false;
    },
    //下线初始化
    goOutOffline() {
      this.$store.state.initStatus = true;
      this.$store.state.initLogin = true;
      this.$store.state.ws = null;
      this.$Message.warning({
        content: "帐号已在其他地方登陆",
        duration: 10
      });
      this.$store.commit("SET_HOME_GET", true);
      this.$store.commit("SET_LIST", []);
      this.$store.commit("SET_NO_READ_COUNT", 0);
      this.$store.commit("SET_INITIALIZER", null);
      this.$router.replace("/");
      // 设置登录窗体的大小
      this.$shell("SetLoginUser", ["", "", "", "420", "460"]);
    },
    // 获取内网IP
    getUserIP() {
      let RTCPeerConnection =
        window.RTCPeerConnection ||
        window.webkitRTCPeerConnection ||
        window.mozRTCPeerConnection;
      if (RTCPeerConnection)
        (() => {
          let rtc = new RTCPeerConnection({
            iceServers: []
          });
          rtc.createDataChannel(""); //创建一个可以发送任意数据的数据通道
          rtc.createOffer(
            offerDesc => {
              //创建并存储一个sdp数据
              rtc.setLocalDescription(offerDesc);
            },
            e => {
              console.log(e);
            }
          );
          rtc.onicecandidate = evt => {
            //监听candidate事件
            if (evt.candidate) {
              let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
              let ip_addr = ip_rule.exec(evt.candidate.candidate)[1];
              if (ip_addr != "192.168.191.1") {
                this.intranetIP = ip_addr;
                console.log(this.intranetIP, "内网IP");
              }
            }
          };
        })();
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        let res = this.$shell("ChangeFormShow", ["0"]);
      }, 700);
    });
    this.getUserIP();
    window.addEventListener("online", () => {
      // 网络由异常到正常时触发
      this.getWebSockect();
      this.getWebSockectTime = setInterval(() => {
        this.getWebSockect();
        if ((this.WebSockectUrl && this.deviceno) || !navigator.onLine) {
          clearInterval(this.getWebSockectTime);
        }
      }, 5000);
      this.offlineFn();
      if (this.$route.path == "/home") {
        this.reconnect();
      } else if (this.onlyLogin) {
        this.lockReconnect = true;
      }
    });
    window.addEventListener("offline", () => {
      // 网络由正常到异常时触发
      clearInterval(this.getWebSockectTime);
      if (this.$route.path == "/home") {
        Notification.closeAll();
        this.$notify({
          title: "错误提示",
          dangerouslyUseHTMLString: true,
          message: `<div>本地网络断开,请稍后重试</div>
                      <button 
                        onclick="reconnection()"
                        style='
                        background-color: #fff;
                        color: #606266;
                        border-radius: 2px;
                        cursor: pointer;
                        border: 1px solid #dcdfe6;
                        padding: 2px 6px;'>重新连接</button>`,
          duration: 0,
          type: "warning",
          showClose: false
        });
      }
      //this.offlineFn()
    });
  },
  created() {
    window.reconnection = this.reconnection;
    this.errorConnectTimer();
    this.getWebSockect();
    this.getWebSockectTime = setInterval(() => {
      this.getWebSockect();
      if ((this.WebSockectUrl && this.deviceno) || !navigator.onLine) {
        clearInterval(this.getWebSockectTime);
      }
    }, 5000);
    window.loginSubmit = this.loginSubmit;
    // 新增账号被挤下线提示
    this.userOutLine = this.$route.query.userOutLine;
    this.initStartInterval();
    this.createLoginTable();
    this.connect();
    window.offlineFn = this.offlineFn;
    window.reconnect = this.connect;
    /**
     * 登录
     * @param {bit} automatic 1为true 0为false 记住账号
     * @param {string} automaticlogon 1 记住密码
     */
    let userInfo = this.operationalDatabase(`SELECT * FROM users_login;`, 1);
    console.log(userInfo, "查询登录表的返回值");
    if (userInfo.list.length > 0) {
      if (userInfo.list[0].automatic) {
        // bol
        this.remember = userInfo.list[0].automatic;
        this.userName = userInfo.list[0].username;
      }
      if (userInfo.list[0].automaticlogon == 1) {
        // string
        if (!this.$store.state.initLogin) {
          this.passWord = userInfo.list[0].password;
          this.autoLogin = userInfo.list[0].automaticlogon;
          this.$store.state.initLogin = true;
          this.isAutoLogin = true; //防止自动登录时点击登录按钮多发请求
          let deviceno = this.deviceno + this.userName;
          this.getWsUrl(deviceno);
          // setTimeout(() => {
          //   this.login();
          // }, 3000);
        } else {
          let auto = this.operationalDatabase(
            `UPDATE users_login SET automaticlogon='0' WHERE _id='1';`
          );
        }
      }
    }
    let infs = this.$shell("DelInfoUserId", []);
    // 新增调用进程ID，为解决账号登录问题
    let clientProess = JSON.parse(this.$shell("GetClientProessId", []));
    if (clientProess.return_code == "TRUE")
      this.proessId = clientProess.return_msg;

    // 登陆中...
    this.dotInterval = setInterval(() => {
      if (this.dotNum == 3) {
        this.dotNum = 1;
      } else {
        this.dotNum++;
      }
    }, 300);
    this.$bus.$on("exitLogin", info => {
      //zk1225新增，接收到退出登录，清除定时器和计数,清除延迟提醒
      this.lockReconnect = true;
      this.outLineSocket && clearInterval(this.outLineSocket);
      this.outLineSocketNum = 0;
      this.netErrorTimeout && clearTimeout(this.netErrorTimeout);
    });
    this.$bus.$on("startLogin", info => {
      console.log(info);
      this.start();
    });
  }
};
</script>
<style scoped>
.download_sub {
  margin-top: 10px;
  text-align: right;
}
</style>
